package org.multi.core;

@FunctionalInterface
public interface Splitter {

    static Splitter of(char delim) {
        return text -> consumer -> {
            int index = text.indexOf(delim);
            if (index < 0) {
                consumer.accept(text);
                return;
            }
            consumer.accept(text.substring(0, index));
            char[] chars = text.toCharArray();
            int length = chars.length, last = index + 1;
            for (int i = last + 1; i < length; i++) {
                if (chars[i] == delim) {
                    consumer.accept(new String(chars, last, i - last));
                    last = i + 1;
                }
            }
            consumer.accept(new String(chars, last, length - last));
        };
    }

    static Splitter of(String delim) {
        return text -> consumer -> {
            if (delim.isEmpty()) {
                consumer.accept(text);
                return;
            }
            int textLen = text.length();
            char[] chars = text.toCharArray();
            int index = text.indexOf(delim);
            if (index < 0) {
                consumer.accept(text);
                return;
            }
            int length = delim.length(), last = index + 1;
            consumer.accept(new String(chars, 0, index));
            while ((index = text.indexOf(delim, last)) > 0) {
                consumer.accept(new String(chars, last, index - last));
                last = index + length;
            }
            consumer.accept(new String(chars, last, textLen - last));
        };
    }

    Multi<String> split(String text);
}
